package com.csaba.connector.citi;

import java.io.StringReader;
import java.util.logging.Logger;

import org.apache.commons.httpclient.NameValuePair;

import com.csaba.connector.ServiceException;
import com.csaba.connector.citi.model.CitiBank;
import com.csaba.connector.citi.model.CitiSession;
import com.csaba.connector.citi.parser.AccountBalanceParser;
import com.csaba.connector.citi.parser.CitiCodes;
import com.csaba.connector.citi.parser.CitiParser;
import com.csaba.connector.model.Account;
import com.csaba.connector.model.Session;
import com.csaba.connector.service.AbstractAccountService;
import com.csaba.util.LoggerHelper;

public class CitiAccountService extends AbstractAccountService
{
	private final static Logger logger = LoggerHelper.getDefaultLogger();

	@Override
	public void execute( final Session session ) throws ServiceException
	{
		if ( !( session instanceof CitiSession ) )
			throw new ServiceException("Unsupported session for Citi services: " + session.getClass().getName());

		final CitiSession citiSession = (CitiSession) session;

		try
		{
			// FIXME reload
			// Creation of account information menu (ACCOUNT INFORMATION)
			final String accountServiceURL = (String) citiSession.getRemoteProperty(CitiCodes.CACHE_ACCOUNTSERVICE_URL);

			if ( accountServiceURL.isEmpty() )
				throw new ServiceException("Service is not initialized correctly.");

			// Query account balance summary (BALANCE SUMMARY)
			// POSTDATA=SELCHOICE=CH1:TK1&TAGTYPE=
			final NameValuePair[] nameValuePairs = new NameValuePair[] { new NameValuePair("SELCHOICE", "CH1:TK1"),
					new NameValuePair("TAGTYPE", "") };

			final String resultBalanceSummary = citiSession.doPost(accountServiceURL, nameValuePairs);
			citiSession.debugFile("resultBalanceSummary", resultBalanceSummary);

			// parse account balance summary
			accounts = AccountBalanceParser.parseAccountList(new StringReader(resultBalanceSummary)); // FIXME use stream as a result of
			// get/put
			if ( accounts.length < 1 )
				throw new IllegalStateException(resultBalanceSummary);

			for ( final Account account : accounts )
			{
				// fix parameters of accounts
				account.setBank(CitiBank.getInstance());
				account.setCustomer(session.getCustomer());

				// TODO try to get the minimum necessary information from the interface
				account.setIBAN("<unknown>");
			}

			logger.fine("Succesful query of account balance summary");

		}
		catch ( final IllegalStateException illegalStateException )
		{
			logger.fine("Error during processing account balances ... Parsing messaging.");
			String message = null;
			try
			{
				// FIXME move to a common place error message parsing
				message = CitiParser.parseErrorMsg(new StringReader(illegalStateException.getMessage()));
			}
			catch ( final Exception ex )
			{
				throw new ServiceException("Error during processing account balances (error message).", ex);
			}

			throw new ServiceException("Error during processing account balances.", message);
		}
		catch ( final Exception ex )
		{
			throw new ServiceException("Unable to download a valid account list.", ex);
		}
	}
}
